package com.liu.common.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.springframework.stereotype.Component;

/**
 * http的工具类
 * 			写一个接口，返回值是Json
 * @author lby
 *
 */
@Component
public class HttpUtil
{
	/**
	 * 模块浏览器发送get请求
	 * @param url 请求网址
	 * @param headMap 请求头
	 * @param paramsMap 请求体
	 * @param responseHeader 响应体的内容
	 * @return  是服务器返回的内容
	 */
	public String methodGet(String urlStr,Map<String,String>headerMap,Map<String,String>paramsMap,
			Map<String,List<String>>responseHeader)
	{
		ConstatFinalUtil.LOGGER.info("==Get请求开始==");
		
		StringBuffer sb = new StringBuffer();
		
		BufferedWriter bw = null ;
		BufferedReader br = null ;
		try
		{
			/*get请求得在url上做处理*/
			sb.delete(0, sb.length());
			sb.append(urlStr);
			if(sb.indexOf("?") == -1)
			{
				sb.append("?");
			}
			for(Entry me:paramsMap.entrySet())
			{
				String key = me.getKey() + "";
				String val = me.getValue() + "";
				sb.append("&" + key + "=" +val);
			}
			urlStr = sb.toString();
			/*得清空sb.因为url拼装的结果和response共用一个sb*/
			sb.delete(0, sb.length());
			ConstatFinalUtil.LOGGER.info("urlStr:{}",urlStr);
			/*创建一个网址*/
			 URL url = new URL(urlStr);
			 /*准备一根管子*/
			 /*创建连接需要打开管子，转换成HttpURl模式*/
			 HttpURLConnection connection = (HttpURLConnection)url.openConnection();
			ConstatFinalUtil.LOGGER.info("===connection:{}=",connection);
			
//			/*默认是get请求*/
//			/*设置超时时间*/
//			/*链接超时；毫秒(网络)*/
//			connection.setConnectTimeout(0);
//			/*读取超时，毫秒(数据量太大)*/
//			connection.setReadTimeout(0);
			
			/*存储请求体*/
			for(Entry me:headerMap.entrySet())
			{
				 String key= me.getKey()+"";
				 String val = me.getValue()+"";
				 connection.setRequestProperty(key, val);
			}
			/*为响应码赋值*/
			responseHeader.putAll(connection.getHeaderFields());
			
			InputStream is = connection.getInputStream();
			br = new BufferedReader(new InputStreamReader(is,"UTF-8"));
			String line= "" ;
			while((line = br.readLine())!=null)
			{
				sb.append(line);
			}
		}catch (Exception e)
		{
			ConstatFinalUtil.LOGGER.error("报错了,url:{}",urlStr,e);
		} finally
		{
			try
			{
				if(br != null )
				{
					br.close();
					br = null ; 
				}
			} catch (IOException e)
			{
				ConstatFinalUtil.LOGGER.error("报错了,url:{}",urlStr,e);
			}
			
			try
			{
				if(bw != null)
				{
					bw.close();
					bw = null ; 
				}
			} catch (IOException e)
			{
				ConstatFinalUtil.LOGGER.error("报错了,url:{}",urlStr,e);
			}
		}
		return sb.toString() ; 
	}
	/**
	 * 模块浏览器发送post请求
	 * @param urlStr 请求网址
	 * @param headerMap 请求头
	 * @param paramsMap 请求体
	 * @param responseHeader 请求发送的总起内容 
	 * @return 服务器返回的内容
	 */
	public String methodPost(String urlStr, Map<String, String> headerMap, 
			Map<String, String> paramsMap,Map<String,List<String>> responseHeader)
	{
		ConstatFinalUtil.LOGGER.info("==post请求开始==");
		
		StringBuilder sb = new StringBuilder();
		
		BufferedWriter bw = null ;
		BufferedReader br = null ; 
		try
		{
			/*创建一根管子*/
			URL url = new URL(urlStr);
			/*准备一根管子*/
			HttpURLConnection connection = (HttpURLConnection)url.openConnection();
			ConstatFinalUtil.LOGGER.info("===connection:{}=",connection);
			
			/*默认是post请求*/
			/*请求打开*/
			connection.setDoInput(true);
			/*请求关闭*/
			connection.setDoOutput(true);
			
//			/* 设置超时时间 */
//			/* 链接超时;毫秒(网络) */
//			connection.setConnectTimeout(10000);
//			/* 读取超时;毫秒(数量量大) */
//			connection.setReadTimeout(10000);
			
			
			/* 存储请求头 */
			for(Entry me : headerMap.entrySet())
			{
				String key = me.getKey() + "" ; 
				String val = me.getValue() + "" ; 
				connection.setRequestProperty(key, val);
			}
			
			/*get请求不能写输入流，但是post恶意写，用输出流添加上就可以*/
			/*存储请求体*/
			OutputStream os = connection.getOutputStream();
			bw = new BufferedWriter(new OutputStreamWriter(os,"UTF-8"));
			sb.delete(0, sb.length());
			for(Entry me : paramsMap.entrySet())
			{
				String key = me.getKey() + "" ; 
				String val = me.getValue() + "" ; 
				sb.append("&" + key + "=" + val) ; 
			}
			/*将请求体添加到输出流里面*/
			bw.write(sb.toString());
			/*控管子*/
			bw.flush();
			/*关管子*/
			bw.close();
			/*打印状态码信息*/
			ConstatFinalUtil.LOGGER.info("==状态码:{}=信息:{}",connection.getResponseCode() ,connection.getResponseMessage());
			sb.delete(0, sb.length());
			
			
			InputStream is = connection.getInputStream();
			br = new BufferedReader(new InputStreamReader(is,"UTF-8"));
			//打印信息
			responseHeader.putAll(connection.getHeaderFields()) ; 
			String line = "" ; 
			while( ( line = br.readLine() ) != null)
			{
				sb.append(line);
			}
		} catch (Exception e)
		{
			ConstatFinalUtil.LOGGER.error("报错了,url:{}",urlStr,e);
		} finally
		{
			try
			{
				if(br != null )
				{
					br.close();
					br = null ; 
				}
			} catch (IOException e)
			{
				ConstatFinalUtil.LOGGER.error("报错了,url:{}",urlStr,e);
			}
			
			try
			{
				if(bw != null)
				{
					bw.close();
					bw = null ; 
				}
			} catch (IOException e)
			{
				ConstatFinalUtil.LOGGER.error("报错了,url:{}",urlStr,e);
			}
		}
		return sb.toString() ; 
	}
}
